<template>
	<view class="check-take-photo" v-if="hasAuth">
		<view class="camera-container">
			<image class="camera-change" @tap="changeCameraPosition" :src="cameraChangeIcon"></image>
			<cover-image class="camera-cover" :src="cameraCircleImg"></cover-image>
			<camera class="camera" :device-position="cameraPosition" frame-size="large" flash="off" @error="refuseCamera"></camera>
			<!-- frame-size="large"拍照图片高清 -->
		</view>
		<view class="check-result">
			<view class="checking" v-if="status === -1">
				<p>请确认图像清晰后，</p>
				<p>再点击下方开始考勤。</p>
			</view>
			<view class="success" v-if="status === 1">
				<u-icon name="checkmark-circle-fill" size="40" color="#07c160" />
				<p class="text">{{ checkType === '1' ? '进场' : '出场' }}考勤成功</p>
				<p class="time">{{ timeNow }}</p>
			</view>
			<view class="failed" v-if="status === 0">
				<u-icon name="error-circle-fill" size="40" color="#FA5151" />
				<p class="text">{{ checkType === '1' ? '进场' : '出场' }}考勤失败</p>
				<p class="time">{{ errMessage }}</p>
			</view>
		</view>
		<view class="take-photo">
			<view class="take-photo-button" v-if="status !== 0" @tap.native="recordAttendance">
				<u-button :loading="btnLoading" :disabled="btnLoading" loading-text="加载中..." type="primary" size="normal">开始考勤</u-button>
			</view>
			<u-button v-else type="info" size="normal" class="take-photo-button failed" @tap.native="returnCheck">返回重新考勤</u-button>
			<view class="sucess-list" @tap.native="toSuccessList">
				<u-button type="success" size="normal">本次考勤成功({{ successList.length }})</u-button>
			</view>
		</view>
	</view>
</template>

<script>
import * as util from '@/pagesA/utils/util.js';
import { common } from '@/pagesA/utils/common.js';
// import cameraCircleImg from '@/pagesA/assets/image/img_camera_circle.png';
// import cameraChangeIcon from '@/pagesA/assets/image/icon_camera_change.png';
const app = getApp();
export default {
	data() {
		return {
			status: -1,
			//-1 拍摄中 1 考勤成功  0 考勤失败
			timeNow: util.formatTime(new Date()),
			checkType: -1,
			cameraPosition: 'front',
			areaUuid: '',
			errMessage: '',
			canUseCamera: true,
			cameraCircleImg: common.imgs.cameraCircleImg,
			cameraChangeIcon: common.imgs.cameraChangeIcon,
			initPhotoNum: 0,
			photoNum: 4,
			//考勤拍照数量
			takePhotoDuration: 50,
			//默认每次拍照相隔时间
			takePhotoDurationAndroid: 300,
			//安卓每次拍照相隔时间
			faceImageList: [],
			//照片列表
			btnLoading: false,
			hasAuth: true,
			successList: []
		};
	},
	onLoad: function (options) {
		// if (app.globalData.projectList.length != 0) {
		//   this.data.hasAuth = true;
		// }
		// if (app.globalData.currentProject && app.globalData.currentProject.projectName) {
		//   this.data.hasAuth = true;
		// }
		// this.setData({
		// 	checkType: options.type,
		// 	areaUuid: options.areaUuid,
		// 	initPhotoNum: this.photoNum,
		// 	hasAuth: app.globalData.commonMethods.hiddenAuth(app)
		// });
		this.checkType = options.type;
		this.areaUuid = options.areaUuid;
		this.initPhotoNum = this.photoNum;
		uni.setNavigationBarTitle({
			title: options.type === '1' ? '进场考勤' : '出场考勤'
		});
	},
	onShow: function () {},
	methods: {
		/**
		 * 切换前置后置摄像头
		 */
		changeCameraPosition() {
			// this.setData({
			// 	cameraPosition: this.cameraPosition === 'front' ? 'back' : 'front'
			// });
			this.cameraPosition = this.cameraPosition === 'front' ? 'back' : 'front';
		},

		/**
		 * 返回重新考勤
		 */
		returnCheck() {
			// this.setData({
			// 	status: -1
			// });
			this.status = -1;
		},

		/**
		 * 相机拍照
		 */
		takePhoto() {
			this.photoNum -= 1;
			if (this.photoNum < 0) {
				let params = {
					areaUuid: this.areaUuid,
					inOrOut: parseInt(this.checkType),
					faceImageList: this.faceImageList
				};
				common.apis.mobileAttendance.checkInV2(params).then(
					(result) => {
						if (result.data.msg) {
							uni.showToast({
								title: result.data.msg,
								icon: 'none',
								duration: 3000
							});
						} else {
							uni.showToast({
								title: '打卡成功',
								icon: 'success',
								duration: 3000
							});
							this.successList.push(result.data);
						}
						// this.setData({
						// 	status: 1,
						// 	btnLoading: false,
						// 	successList: this.successList
						// });
						this.status = 1;
						this.btnLoading = false;
						// app.globalData.hasTakePhoto = true; //显示插屏广告
						// setTimeout(() => {
						//   wx.reLaunch({
						//     url: '/pages/home/index',
						//   });
						// }, 2500);
					},
					(err) => {
						// this.setData({
						// 	status: 0,
						// 	btnLoading: false,
						// 	errMessage: err.data ? err.data.msg : '打开失败请重试'
						// });
						this.status = 0;
						this.btnLoading = false;
						this.errMessage = err.data ? err.data.msg : '打开失败请重试';
					}
				);
			} else {
				// console.log(`第${this.data.photoNum}张照片拍照`);
				this.cameraContext.takePhoto({
					quality: 'high',
					//高质量的图片
					success: (res) => {
						// console.log(`第${this.data.photoNum}张照片拍照成功`);
						let tempImagePath = res.tempImagePath;
						if (!tempImagePath) {
							uni.showToast({
								title: '请打开微信手机存储权限，或勿使用微信分身功能',
								icon: 'none',
								duration: 3000
							});
							// this.setData({
							// 	btnLoading: false
							// });
							this.btnLoading = false;
							return;
						}
						const fs = uni.getFileSystemManager();
						fs.readFile({
							filePath: tempImagePath,
							encoding: 'base64',
							success: (res) => {
								this.faceImageList.push(res.data);
								const systemInfo = uni.getSystemInfoSync();
								const platform = systemInfo.platform;
								if (platform == 'android') {
									//安卓定时器
									setTimeout(() => {
										this.takePhoto();
									}, this.takePhotoDurationAndroid);
								} else {
									setTimeout(() => {
										this.takePhoto();
									}, this.takePhotoDuration);
								}
							},
							fail: (err) => {
								// this.setData({
								// 	btnLoading: false
								// });
								this.btnLoading = false;
								uni.showToast({
									title: '微信发生错误，错误码:' + (err.errno ? err.errno : '800031'),
									icon: 'none',
									duration: 2000
								});
							}
						});
					},
					fail: (err) => {
						// this.setData({
						// 	btnLoading: false
						// });
						this.btnLoading = false;
					}
				});
			}
		},

		/**
		 * 开始考勤
		 */
		recordAttendance() {
			if (this.btnLoading) {
				return;
			}
			// this.setData({
			// 	btnLoading: true
			// });
			this.btnLoading = true;
			this.photoNum = this.initPhotoNum;
			this.cameraContext = uni.createCameraContext();
			this.faceImageList = [];
			uni.showLoading({
				title: '打卡中'
			});
			this.takePhoto();
		},

		//拒绝使用摄像头触发
		refuseCamera() {
			uni.showModal({
				title: '您没有打开摄像头权限',
				content: '是否前往设置页面手动开启',
				success: function (res) {
					if (res.confirm) {
						uni.openSetting({
							withSubscriptions: true
						});
					} else {
						uni.showToast({
							icon: 'none',
							title: '您拒绝了开启摄像头权限'
						});
					}
				},
				fail: function (e) {
					console.log(e);
				}
			});
		},

		toSuccessList() {
			//考勤成功列表
			if (this.successList.length == 0) {
				common.message.toast('暂无考勤成功数据');
				return;
			}
			app.globalData.hasTakePhotoData = true;
			app.globalData.takePhotoData = this.successList;
			uni.navigateTo({
				url: '/pagesA/pages/attendance/successList/successList'
			});
		}
	}
};
</script>
<style>
page {
	width: 100%;
	height: 100%;
}

.check-take-photo {
	width: 100%;
	height: 100%;
}

.check-take-photo .camera-container {
	margin-top: 60rpx;
	margin-bottom: 60rpx;
	width: 100%;
	height: 480rpx;
	display: flex;
	align-items: center;
	justify-content: space-around;
}

.check-take-photo .camera-container .camera-change {
	width: 72rpx;
	height: 72rpx;
	position: absolute;
	right: 30rpx;
	top: 60rpx;
}

.check-take-photo .camera-container .camera-cover {
	width: 500rpx;
	height: 500rpx;
	position: absolute;
	z-index: 10;
}

.check-take-photo .camera-container .camera {
	width: 480rpx;
	height: 480rpx;
}

.check-take-photo .check-result {
	width: 100%;
}

.check-take-photo .check-result .checking {
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	align-items: center;
	font-size: 32rpx;
	font-weight: 500;
	color: #4b5680;
	line-height: 48rpx;
}

.check-take-photo .check-result .success {
	width: 100%;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.check-take-photo .check-result .success .icon {
	font-size: 80rpx;
	color: #07c160;
}

.check-take-photo .check-result .success .text {
	font-size: 36rpx;
	font-weight: 600;
	color: #1e253f;
	line-height: 50rpx;
	margin: 36rpx 0 16rpx 0;
}

.check-take-photo .check-result .success .time {
	font-size: 36rpx;
	font-weight: 500;
	color: #4b5680;
	line-height: 50rpx;
}

.check-take-photo .check-result .failed {
	width: 100%;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.check-take-photo .check-result .failed .icon {
	font-size: 80rpx;
	color: #fa5151;
}

.check-take-photo .check-result .failed .text {
	font-size: 36rpx;
	font-weight: 600;
	color: #1e253f;
	line-height: 50rpx;
	margin: 36rpx 0 16rpx 0;
}

.check-take-photo .check-result .failed .time {
	font-size: 36rpx;
	font-weight: 500;
	color: #4b5680;
	line-height: 50rpx;
}

.check-take-photo .take-photo {
	width: 80%;
	position: fixed;
	bottom: 60rpx;
	left: 50%;
	transform: translateX(-50%);
}

.check-take-photo .take-photo .sucess-list {
	margin-top: 42rpx;
}
</style>
